package edu.jd.movieplatform.common.base;


import com.fasterxml.jackson.databind.ObjectMapper;
import edu.jd.movieplatform.common.*;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//表示拦截以urlPatterns内的路径
@WebFilter(urlPatterns = {"/security/*","/admin/*","/c_admin/*"})
public class MSecurityFilter implements Filter {
    //放行通过是/xx/uu的路径的请求
    private static final String[] freePaths = {"/security/m_login","/m_home","/security/login","/security/home","/security/register","/security/m_register"};
    //放行通过带有/xx前路径的请求
    private static final String[] freePrefixPaths = {"/css","/fonts","/images","/js","/layer","/security/home"};


    private static boolean isFreePath(String thePath){
        for(String path:freePaths){
            if(path.equals(thePath)){
                return true;
            }
        }
        return false;
    }

    private static boolean hasPrefix(String thePath){
        for(int i=0;i<freePrefixPaths.length;i++){
            if(thePath.startsWith(freePrefixPaths[i])){
                return true;
            }
        }
        return false;
    }

    private static boolean isAjax(HttpServletRequest req){
        return "XMLHttpRequest".equals(req.getHeader("X-Requested-With"));

    }


    @Resource
    private CommonService commonService;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String path = request.getServletPath();

        if(isFreePath(path) || hasPrefix(path)){
            filterChain.doFilter(request,response);
            return;
        }
        String method = request.getMethod();// GET、POST、options等等（options请求是预检请求，在post等发送前发送，用于检查接口是否可用）
        if(method.equalsIgnoreCase("options")){
            filterChain.doFilter(request,response);
            return;
        }

        String clientToken = request.getHeader(Constants.HEADER_TOKEN);

        try {
            MTokenUtils.verifyToken(clientToken,commonService);

        } catch (Exception e) {
            e.printStackTrace();
            Utils.outJson(response, Result.fail(Result.ERR_CODE_UNLOGIN_ADMIN,e.getMessage()));
            //response.sendRedirect("/m_login");
            return;
        }

        try{
            filterChain.doFilter(servletRequest,servletResponse);
        }catch (Exception e) {
            e.printStackTrace();
            Utils.outJson(response, Result.fail(Result.ERR_CODE_SYS,e.getMessage()));
        }
    }

    @Override
    public void destroy() {

    }
}
